package com.codewsq.exer.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class WindowToThread extends Thread {

    private static int ticket = 100;
    private static Lock lock = new ReentrantLock(); // 锁也必须保证是共享的

    @Override
    public void run() {
        while (true) {
            try {
                sleep(100);
                lock.lock();
                if (ticket > 0) {
                    System.out.println(getName() + "售票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}


public class TicketSalesToThread {

    public static void main(String[] args) {
        WindowToThread t1 = new WindowToThread();
        WindowToThread t2 = new WindowToThread();
        WindowToThread t3 = new WindowToThread();

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
